﻿using DevExpress.XtraEditors;
using System;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static BW.Mes.WinForms.BasicData.CustomerForm;
using System.Collections.Generic;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddCustomerForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        public AddCustomerForm()
        {
            InitializeComponent();
            this.Load += AddCustomerForm_AutoGenCustomerCode;
            // 在构造函数或Load事件中添加textEditMsg.EditValueChanged事件，事件内统计字符数、限制50、更新labelControlCount。
            textEditMsg.EditValueChanged += TextEditMsg_EditValueChanged;
        }
        private async void AddCustomerForm_AutoGenCustomerCode(object sender, EventArgs e)
        {
            // 自动生成客户编号
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"KH{today}";
            int maxSerial = 0;
            try
            {
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Customer/GetCustomer");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var jsonObject = JObject.Parse(json);
                    var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                    if (listToken != null)
                    {
                        var customers = JsonConvert.DeserializeObject<List<CustomerModel>>(listToken.ToString());
                        if (customers != null)
                        {
                            foreach (var item in customers)
                            {
                                string code = item.CustomerCode;
                                if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                {
                                    string serialStr = code.Substring(prefix.Length);
                                    if (int.TryParse(serialStr, out int serial))
                                    {
                                        if (serial > maxSerial) maxSerial = serial;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textEditCode.Text = newCode;
            textEditCode.Properties.ReadOnly = true;
        }
        private async void btnOK_Click(object sender, EventArgs e)
        {
            // 在保存/确定按钮事件中添加如下校验：
            string phone = textEditPhone.Text.Trim();
            if (phone.Length != 11 || !System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{11}$"))
            {
                XtraMessageBox.Show("联系电话必须为11位数字！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var model = new
            {
                CustomerCode = textEditCode.Text,
                CustomerName = textEditName.Text,
                Abbreviation = textEditAbbreviation.Text,
                Phone = textEditPhone.Text,
                Address = textEditAddress.Text,
                USCC = textEditUSCC.Text,
                Status = comboBoxEditStatus.Text,
                CustomerMsg = textEditMsg.Text,
                CreatedBy = "wyj"
            };
            string jsonData = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{_apiBaseUrl}/T2/Customer/AddCustomer", content);
            if (response.IsSuccessStatusCode)
            {
                XtraMessageBox.Show("新增成功！");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                var errorMsg = await response.Content.ReadAsStringAsync();
                XtraMessageBox.Show($"新增失败！\n状态码: {response.StatusCode}\n内容: {errorMsg}");
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddCustomerForm_Load(object sender, EventArgs e)
        {

        }

        private void TextEditMsg_EditValueChanged(object sender, EventArgs e)
        {
            TextEdit textEdit = sender as TextEdit;
            if (textEdit != null)
            {
                string text = textEdit.Text;
                if (text.Length > 50)
                {
                    textEdit.Text = text.Substring(0, 50);
                }
                labelControlCount.Text = $"字符数: {textEdit.Text.Length}/50";
            }
        }
    }
}